//
//  PictureSelectorController.swift
//  sinaWeibo
//
//  Created by liii on 16/8/9.
//  Copyright © 2016年 liii. All rights reserved.
//

import UIKit

// 重用标识
private let PictureCellId = "PictureCellId"
// Cell间距
private let PictureCellMargin: CGFloat = 1
// 每行Cell的个数
private let columImageCount: CGFloat = 4
// 最大可选图片数
private let maxImageCount = 9

class PictureSelectorController: UICollectionViewController {
    
    // 用于存放，用户从相册选择的图片
    var imageList = [UIImage]()

    init() {
        // layout设定及计算
        let w = (screenWidth - (columImageCount + 1) * PictureCellMargin) / columImageCount
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: w, height: w)
        layout.minimumLineSpacing = PictureCellMargin
        layout.minimumInteritemSpacing = PictureCellMargin
        layout.sectionInset = UIEdgeInsets(top: PictureCellMargin, left: PictureCellMargin, bottom: 0, right: PictureCellMargin)
        super.init(collectionViewLayout: layout)
        
        self.collectionView?.backgroundColor = UIColor.whiteColor()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 注册Cell
        self.collectionView!.registerClass(PictureSelectorCell.self, forCellWithReuseIdentifier: PictureCellId)
    }
}

// 数据源及代理
extension PictureSelectorController {
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // 监控用户选择图片的数量，如果达到上限
        let delta = imageList.count == maxImageCount ? 0 : 1
        return imageList.count + delta
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureCellId, forIndexPath: indexPath) as! PictureSelectorCell
        
        // 代理设计模式：No.5(成为代理)
        cell.selectorDelegate = self
        cell.backgroundColor = UIColor.RGBColor()
        
        if indexPath.item == imageList.count {
            cell.image = nil
        } else {
            cell.image = imageList[indexPath.item]
        }
        
        return cell
    }
    
}

// 代理设计模式：No.6(遵守协议)
extension PictureSelectorController: PictureSelectorCellDelegate {

    // 代理设计模式：No.7(实现代理方法)
    func userWillAddPicture() {
        // 添加图片
        let picker = UIImagePickerController()
        picker.delegate = self
        picker.allowsEditing = true
        // 弹出界面
        presentViewController(picker, animated: true, completion: nil)
    }
    func userWillDelPicture(cell: PictureSelectorCell) {
        // 获取要删除的 Cell 所在行，将数据从数组中移除，并刷新界面
        if let indexPath = self.collectionView?.indexPathForCell(cell) {
            self.imageList.removeAtIndex(indexPath.item)
            self.collectionView?.reloadData()
        }
    }
}

// 遵守 UIImagePickerControllerDelegate 协议
extension PictureSelectorController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        // 保存图片
        imageList.append(image)
        // 刷新界面
        collectionView?.reloadData()
        // 关闭界面
        self.dismissViewControllerAnimated(true, completion: nil)
    }
}

// 代理设计模式：No.1(定义协议)
protocol PictureSelectorCellDelegate: NSObjectProtocol {

    // 代理设计模式：No.2(声明协议方法)
    func userWillAddPicture()
    func userWillDelPicture(cell: PictureSelectorCell)
}

// 自定义Cell
class PictureSelectorCell: UICollectionViewCell {
    
    // 获取数据
    var image: UIImage? {
        didSet {
            // 吐过图片为空，隐藏删除按钮
            delBtn.hidden = image == nil
            // 图片不为空，设置给图片
            addBtn.setImage(image, forState: .Normal)
        }
    }
    
    // 代理设计模式：No.3(设置代理属性)
    weak var selectorDelegate: PictureSelectorCellDelegate?
    
    // 代理设计模式：No.4(调用代理方法)
    @objc private func addBtnDidClick() {
        if image == nil {
            selectorDelegate?.userWillAddPicture()
        }
    }
    @objc private func delBtnDidClick() {
        selectorDelegate?.userWillDelPicture(self)
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
  
    private func setupUI() {
    
        contentView.addSubview(addBtn)
        contentView.addSubview(delBtn)
        
        addBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
        delBtn.snp_makeConstraints { (make) -> Void in
            make.top.right.equalTo(contentView)
        }
        
        addBtn.addTarget(self, action: "addBtnDidClick", forControlEvents: .TouchUpInside)
        delBtn.addTarget(self, action: "delBtnDidClick", forControlEvents: .TouchUpInside)
        
        // 设置图片显示模式
        addBtn.imageView?.contentMode = .ScaleAspectFill
    }
    
    // 添加按钮
    private lazy var addBtn: UIButton = UIFactory.buttonWithImage(nil, backgroundImage: "compose_pic_add")
    // 删除按钮
    private lazy var delBtn: UIButton = UIButton.buttonWithImage("compose_photo_close", backgroundImage: nil)
}